package com.push.web.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class ApiRequest {
    public JSONObject goPost(String postUrl,JSONObject params){
        JSONObject returnObject = null;
        CloseableHttpResponse response = null;
        String result = "";
        //创建 httpClient对象
        CloseableHttpClient httpClient = null;
        //创建一个实例
        httpClient = HttpClients.createDefault();
        //创建HttpPost连接实例
        HttpPost httpPost = new HttpPost(postUrl);
        //设置请求参数，将连接超时的时间改长；从35000修改为100000；
        RequestConfig postConfig = RequestConfig.custom().setConnectionRequestTimeout(100000).setConnectTimeout(100000).build();

        httpPost.setConfig(postConfig);
        httpPost.setHeader(  "Content-Type", "application/json");

        //判断参数
        if(null != params && params.size() > 0){
            StringEntity entity = new StringEntity(params.toString(), "utf-8");
            entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            // 将参数放入请求之中
            httpPost.setEntity(entity);
//            log.info("Post URL :" + postUrl);
//            log.info("Post Params :" + params.toString());
        }
        try {
            // httpClient对象执行post请求,并返回响应参数对象
            response = httpClient.execute(httpPost);
            // 从相应对象中获取相应内容
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
            returnObject = JSONObject.parseObject(result);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 关闭资源
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != response){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return returnObject;
    }
}
